<template>
  <el-card class="box-card">
    <!-- 头部插槽 -->
    <template #header>
      <div class="card-header">
        <span>就诊人管理</span>
        <el-button class="button" type="primary" :icon="User" @click="addUser">添加就诊人</el-button>
      </div>
    </template>
    <!-- 就诊人管理模块展示：就诊人信息结构-->
    <div class="visitors" v-if="!scene">
      <Visitor class=" item" v-for="(user, index) in userArr" :key="user.id" :user="user" :index="index"
        :currentIndex="currentIndex" @changeScene="changeScene" @removeUser="removeUser" />
    </div>
    <!-- 就诊人管理模块展示：添加就诊人/修改已有的就诊人结构-->
    <div class="form" v-if="scene">
      <el-divider content-position="left">就诊人信息</el-divider>
      <el-form style="width: 60%;margin: 10px auto;">
        <el-form-item label="用户姓名">
          <el-input placeholder="请输入用户姓名" v-model="userParams.name"></el-input>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-select placeholder="请选择证件类型" style="width: 100%;" v-model="userParams.certificatesType">
            <el-option v-for="item in certationArr" :key="item.id" :lable="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input placeholder="请输入证件号码" v-model="userParams.certificatesNo"></el-input>
        </el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="userParams.sex">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="userParams.birthdate" value-format="YYYY-MM-DD" type="date" placeholder="请选择出生日期" />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input placeholder="请输入手机号码" v-model="userParams.phone"></el-input>
        </el-form-item>
      </el-form>
      <el-divider content-position="left">建档信息（完善后部分医院首次就诊不排队建档）</el-divider>
      <el-form style="width: 60%;margin:10px auto; ">
        <el-form-item label="婚姻状况">
          <el-radio-group v-model="userParams.isMarry">
            <el-radio :value="1">已婚</el-radio>
            <el-radio :value="0">未婚</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自费医保">
          <el-radio-group v-model="userParams.isInsure">
            <el-radio :value="1">自费</el-radio>
            <el-radio :value="0">医保</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="当前住址">
          <el-cascader :props="props" v-model="userParams.addressSelected" />
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input placeholder="请输入详细地址" v-model="userParams.address"></el-input>
        </el-form-item>
      </el-form>
      <el-divider content-position="left">联系人信息（选填）</el-divider>
      <el-form style="width: 60%;margin: 10px auto;" label-width="80">
        <el-form-item label="用户姓名">
          <el-input placeholder="请输入用户姓名" v-model="userParams.contactsName"></el-input>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-select placeholder="请选择证件类型" style="width: 100%;" v-model="userParams.contactsCertificatesType">
            <el-option v-for="item in certationArr" :key="item.id" :lable="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input placeholder="请输入证件号码" v-model="userParams.contactsCertificatesNo"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input placeholder="请输入手机号码" v-model="userParams.contactsPhone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="submit">提交</el-button>
          <el-button size="default" @click="reset">重写</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script setup lang="ts" name="Patient">
//引入icon图标
import {
  User
} from '@element-plus/icons-vue'
//引入组合式API
import { onMounted, ref, reactive, watch } from 'vue'
//引入请求就诊人信息的请求方法和ts类型
//@ts-ignore
import { reqGetUser } from '@/api/hospital'
//@ts-ignore
import type { UserResponseData, UserArr } from '@/api/hospital/type'
//引入请求和ts类型
//@ts-ignore
import { reqCertationType, reqCity, reqAddOrUpdateUser, reqRemoveUser } from '@/api/user'
//@ts-ignore
import type { CertationTypeResponseData, CertationArr, AddOrUpdateUser } from '@/api/user/type'
//引入级联选择器的tS类型 和 处理消息的提示
import { ElMessage, type CascaderProps } from 'element-plus'
//引入路由 路由器
import { useRoute, useRouter } from 'vue-router'

//就诊人信息
let userArr = ref<UserArr>([] as UserArr)
//当前选中的就诊人索引值（默认是 -1，表示一个也没有选中）(这里不给它绑定事件，使其为-1，让子组件永远不展示”已选中“)
let currentIndex = ref<number>(-1)
//添加就诊人，修改已有就诊人信息结构是否展示
let scene = ref<boolean>(false)
//证件类型
let certationArr = ref<CertationArr>([] as CertationArr)
//收集新增就诊人的数据
let userParams = reactive<AddOrUpdateUser>({
  name: '',
  certificatesType: '',
  certificatesNo: '',
  sex: 0,
  birthdate: '',
  phone: '',
  isMarry: 0,
  isInsure: 0,
  addressSelected: [],
  address: '',
  contactsName: '',
  contactsCertificatesType: '',
  contactsCertificatesNo: '',
  contactsPhone: ''
})
//路由 路由器
let $route = useRoute()
let $router = useRouter()

//监听全部就诊人的数据
watch(
  () => userArr.value,
  () => {
    if ($route.query.type == 'edit') {
      let user = userArr.value.find((item: any) => {
        return item.id === $route.query.id
      })
      Object.assign(userParams, user)
    }
  })

//发送请求获取就诊人信息
const getUser = async () => {
  let result: UserResponseData = await reqGetUser()
  if (result.code == 200) {
    userArr.value = result.data
  }
}
//发送请求获取证件类型
const getCertationType = async () => {
  let result: CertationTypeResponseData = await reqCertationType()
  if (result.code == 200) {
    certationArr.value = result.data
  }
}
//组件挂载时：
onMounted(() => {
  //发送请求获取就诊人信息
  getUser()
  // 发送请求获取证件类型
  getCertationType()
  //判断：当前这个路由组件是从挂号组件跳转而来，切换到添加/修改就诊人结构
  if ($route.query.type == 'add' || $route.query.type == 'edit') {
    //切换到 添加就诊人 结构
    scene.value = true
  }
})
//点击添加就诊人按钮的回调
const addUser = () => {
  //清空上一次的数据
  reset()
  //添加修改就诊人信息结构展示
  scene.value = true
}
//就诊人子组件自定义事件的回调
const changeScene = (user: AddOrUpdateUser) => {
  //切换到添加就诊人结构
  scene.value = true
  //收集子组件触发自定义事件回显的就诊人信息
  Object.assign(userParams, user)
}
//就诊人子组件自定义事件的回调
const removeUser = async (id: number) => {
  try {
    //发送请求删除该id的用户
    await reqRemoveUser(id)
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    //重新发送请求获取用户数据
    getUser()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '删除失败'
    })
  }
}
//级联选择器提供的数据
const props: CascaderProps = {
  //懒加载
  lazy: true,
  //加载级联选择器数据的方法
  async lazyLoad(node: any, resolve: any) {
    //发送请求获取城市数据
    let result: any = await reqCity(node.data.id || "86")
    //整理数据
    let showData = result.data.map((item: any) => {
      return {
        id: item.id,
        label: item.name,
        value: item.value,
        leaf: !item.hasChildren
      }
    })
    //注入组件需要展示的数据
    resolve(showData)
  },
}
//点击提交按钮的回调：发送请求提交数据
const submit = async () => {
  try {
    await reqAddOrUpdateUser(userParams)
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '新增成功'
    })
    //如果从挂号跳转而来：成功提交数据后跳回去
    //如果是当前路由组件提交按钮的回调：更新或新增成功后应该切换为就诊人信息结构
    if ($route.query.type == 'add') {
      $router.back()
    } else {
      scene.value = false
    }
    //重新发送请求获取就诊人信息
    getUser()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新失败' : '新增失败'
    })
  }
}
//清空表单数据
const reset = () => {
  Object.assign(userParams, {
    id: null,
    name: '',
    certificatesType: '',
    certificatesNo: '',
    sex: 0,
    birthdate: '',
    phone: '',
    isMarry: 0,
    isInsure: 0,
    addressSelected: [],
    address: '',
    contactsName: '',
    contactsCertificatesType: '',
    contactsCertificatesNo: '',
    contactsPhone: ''
  })
}
</script>

<style scoped lang="scss">
.box-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .visitors {
    display: flex;
    flex-wrap: wrap;

    .item {
      width: 32%;
      margin: 5px;
    }
  }
}
</style>